package com.channel.temperature.collect.ui.activity

import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.AdapterView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.HBluetooth
import com.hjy.bluetooth.entity.BluetoothDevice
import com.hjy.bluetooth.exception.BluetoothException
import com.hjy.bluetooth.inter.BleNotifyCallBack
import com.hjy.bluetooth.inter.ConnectCallBack
import com.hjy.bluetooth.inter.ScanCallBack
import com.hjy.bluetooth.inter.SendCallBack
import com.hjy.bluetooth.operator.abstra.Sender
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.channel.temperature.collect.R
import com.channel.temperature.collect.app.base.BaseActivity
import com.channel.temperature.collect.app.ble.BLECommand
import com.channel.temperature.collect.app.ext.initBack
import com.channel.temperature.collect.app.util.MyUtil
import com.channel.temperature.collect.databinding.ActivityBluetoothBinding
import com.channel.temperature.collect.ui.adapter.MyAdapter
import com.channel.temperature.collect.ui.viewmodel.BlueToothModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.ext.getStringExt
import me.hgj.mvvmhelper.ext.setOnclick
import me.hgj.mvvmhelper.util.XLog
import java.util.ArrayList


class ClassicActivity : BaseActivity<BlueToothModel, ActivityBluetoothBinding>(),
    AdapterView.OnItemClickListener {
    private val TAG = "BlueToothActivity"

    var mHBluetooth: HBluetooth? = null
    private var mAdapter: MyAdapter? = null
    private var list: ArrayList<BluetoothDevice> = ArrayList()
    private var mSender: Sender? = null
    private lateinit var registerForActivityResult: ActivityResultLauncher<Intent>
    override fun initView(savedInstanceState: Bundle?) {
        //初始化toolbar
        mToolbar.initBack(getStringExt(R.string.bt_test)) {
            finish()
        }
        checkPermission()
        checkBlueToothAdapter()
        registerForActivityResult =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                XLog.e("这里回调了")
                checkBlueToothAdapter()
            }
        mAdapter = MyAdapter(this, list)
        mBind.rvBt.adapter = mAdapter
        mBind.rvBt.onItemClickListener = this
    }

    override fun onBindViewClick() {

        //绑定点击事件
        setOnclick(mBind.async, mBind.rescan) {
            when (it) {
                mBind.async -> {
                    var testmsg = "你在干嘛"

                    XLog.e(
                        "发送 数据长度length" + testmsg.length + "    " + MyUtil.bytes2Hex(
                            testmsg.toByteArray()
                        )
                    )

                    mSender?.send(testmsg.toByteArray(), object : SendCallBack {
                        override fun onSending(command: ByteArray) {
                            Log.e(TAG, "命令发送中... " + String(command))
                        }

                        override fun onSendFailure(bleException: BluetoothException) {
                            Log.e("mylog", "发送命令失败->" + bleException.message)
                        }
                    })
                }

                mBind.rescan -> {
                    XLog.e("重新扫描")
                    scanWithTimeUse(1);
                }
            }
        }
    }

    var totalSize = 0
    var resultLength = 0
    fun initListener() {
        HBluetooth.getInstance().setReceiver { dataInputStream, result -> //设备发过来的数据将在这里出现
            Log.e(
                "mylog",
                result.size.toString() + "收到蓝牙设备返回数据->" + MyUtil.bytes2Hex(result)
            )
//            totalSize++
//            resultLength += result.size
//            if (result.size == 427) {
//                Log.e(
//                    "mylog",
//                    "最后一包数据后的统计->，总包数： " + totalSize + " , 最后总长度 ： " + resultLength
//                )
//                totalSize = 0
//                resultLength = 0
//            } else {
//                Log.e(
//                    "mylog", "还在接收中->，当前包数： " + totalSize + " , 当前总 ： " + resultLength
//                )
//            }
        }
    }

    private fun checkBlueToothAdapter() {
        var mAdpter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (!mAdpter.isEnabled) {
//            ToastUtils.show("没有蓝牙权限")
            MessageDialog.show(
                "提示", "跳转到设置界面打开蓝牙？", "OK", "Cancel"
            ).okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                ToastUtils.show("点击了ok")
                dialog.dismiss()
                registerForActivityResult.launch(Intent(Settings.ACTION_BLUETOOTH_SETTINGS))
                true
            }
        } else {
//            ToastUtils.show("有蓝牙权限")
        }


    }

    private fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            Log.e("高版本", "高版本");
            XXPermissions.with(this) // 申请单个权限
                .permission(Permission.BLUETOOTH_CONNECT).permission(Permission.BLUETOOTH_SCAN)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        if (all) {
                            mHBluetooth = HBluetooth.getInstance()

                            //请填写你自己设备的UUID
                            //低功耗蓝牙才需要如下配置BleConfig,经典蓝牙不需要new HBluetooth.BleConfig()
                            val bleConfig = HBluetooth.BleConfig()
                            bleConfig.withServiceUUID("6e400001-b5a3-f393-e0a9-e50e24dcca9e")
                                .withWriteCharacteristicUUID("6e400002-b5a3-f393-e0a9-e50e24dcca9e")
                                .withNotifyCharacteristicUUID("6e400003-b5a3-f393-e0a9-e50e24dcca9e")

                            mHBluetooth?.let {
                                it.enableBluetooth().bleConfig = bleConfig
                            }
                            initListener()
                            scanWithTimeUse(1)
                        } else {
                        }
                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(
                                this@ClassicActivity, permissions
                            )
                        } else {
                            ToastUtils.show("请通过权限后再操作应用")
                        }
                    }
                })
        } else {
            Log.e("低版本", "低版本");
            XXPermissions.with(this) // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION) // 申请多个权限
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        if (all) {
                            mHBluetooth = HBluetooth.getInstance()
                            //请填写你自己设备的UUID
                            //低功耗蓝牙才需要如下配置BleConfig,经典蓝牙不需要new HBluetooth.BleConfig()
                            val bleConfig = HBluetooth.BleConfig()
                            bleConfig.withServiceUUID("6e400001-b5a3-f393-e0a9-e50e24dcca9e")
                                .withWriteCharacteristicUUID("6e400002-b5a3-f393-e0a9-e50e24dcca9e")
                                .withNotifyCharacteristicUUID("6e400003-b5a3-f393-e0a9-e50e24dcca9e")
                            mHBluetooth?.let {
                                it.enableBluetooth().bleConfig = bleConfig
                            }
                            initListener()
                            scanWithTimeUse(1)
                        } else {
                        }
                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        if (never) {
                            ToastUtils.show("android12以下 被永久拒绝授权，请手动授予权限")
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(
                                this@ClassicActivity, permissions
                            )
                        } else {
                            ToastUtils.show("请通过权限后再操作应用")
                        }
                    }
                })
        }


    }

    private fun scanWithTimeUse(type: Int) {
        //扫描蓝牙设备，扫描6秒就自动停止扫描
        mHBluetooth?.scan(type, 6000, object : ScanCallBack {
            override fun onScanStart() {
                Log.e(TAG, "开始扫描")
            }

            override fun onScanning(
                scannedDevices: MutableList<BluetoothDevice>?,
                currentScannedDevice: BluetoothDevice?
            ) {
                Log.e(TAG, "扫描中");
                if (scannedDevices != null && scannedDevices.size > 0) {
                    list.clear()
                    list.addAll(scannedDevices)
                    mAdapter?.notifyDataSetChanged()
                }
            }

            override fun onError(errorType: Int, errorMsg: String?) {
                Log.e(TAG, "errorType:" + errorType + "  errorMsg:" + errorMsg);
            }

            override fun onScanFinished(bluetoothDevices: MutableList<com.hjy.bluetooth.entity.BluetoothDevice>?) {
                Log.e(TAG, "扫描结束");
                ToastUtils.show("扫描结束")
                if (bluetoothDevices != null && bluetoothDevices.size > 0) {
                    list.clear();
                    list.addAll(bluetoothDevices);
                    mAdapter?.notifyDataSetChanged();
                }
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        mHBluetooth?.release();
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        val device: BluetoothDevice = list[position]
        //调用连接器连接蓝牙设备
        mHBluetooth?.connect(device, object : ConnectCallBack {
            override fun onConnecting() {
                Log.e(TAG, "连接中...")
            }

            override fun onConnected(sender: Sender) {
                Log.e(TAG, "连接成功,isConnected:" + mHBluetooth!!.isConnected)
                //调用发送器发送命令
                val test = "你好你在干嘛"
                mSender = sender
            }

            override fun onDisConnecting() {
                Log.e(TAG, "断开连接中...")
            }

            override fun onDisConnected() {
                Log.e(TAG, "已断开连接,isConnected:" + mHBluetooth!!.isConnected)
            }

            override fun onError(errorType: Int, errorMsg: String) {
                Log.e(TAG, "错误类型：$errorType 错误原因：$errorMsg")
            } //低功耗蓝牙才需要BleNotifyCallBack
            //经典蓝牙可以只调两参方法connect(BluetoothDevice device, ConnectCallBack connectCallBack)
        }, object : BleNotifyCallBack {
            override fun onNotifySuccess() {
                Log.e(TAG, "打开通知成功")
                CoroutineScope(Dispatchers.Default).launch {
                    delay(1000)
                    var bufData = BLECommand.reset()
                    XLog.e("得到的buf " + MyUtil.bytes2Hex(bufData))
                    mSender?.send(bufData, object : SendCallBack {
                        override fun onSending(command: ByteArray) {
                            Log.e(TAG, "命令发送中... " + String(command))
                        }

                        override fun onSendFailure(bleException: BluetoothException) {
                            Log.e("mylog", "发送命令失败->" + bleException.message)
                        }
                    })
                }

            }

            override fun onNotifyFailure(bleException: BluetoothException) {
                Log.e(TAG, "打开通知失败：" + bleException.message)
            }
        })
    }

}